<template>
	<view class="cc-date-range-picker" :style="{
		'--light-color': $theme.lightColor
	}">
		<view class="mm-picker__content" @click="handleOpen">
			<view :class="['mm-picker__text', disabled ? 'mm-picker__placeholder' : '']" v-if="value.length > 0">{{value[0]}} ~ {{value[1]}}</view>
			<view class="mm-picker__placeholder" v-else>{{placeholder}}</view>
			<!-- #ifdef APP-PLUS -->
			<w-icon top="-4" name="calendar" size="28" wrap-width="50" color="lightColor" align="flex-end"></w-icon>
			<!-- #endif -->
			<!-- #ifdef MP-WEIXIN -->
			<w-icon top="10" name="calendar" size="28" wrap-width="50" color="lightColor" align="flex-end"></w-icon>
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<w-icon top="1" name="calendar" size="28" wrap-width="50" color="lightColor" align="flex-end"></w-icon>
			<!-- #endif -->
		</view>
		<w-calendar 
			v-model="show" 
			mode="range"
			@change="change"
			:min-date="minDate"
			:max-date="maxDate"
			:toolTip="placeholder"
			:activeBgColor="activeBgColor"
			:rangeColor="rangeColor"
			:rangeBgColor="rangeBgColor"
			:defaultData="defaultData"
		></w-calendar>
	</view>
</template>

<script>
	/**
	 * 日期范围picker双向绑定封装
	 */
	import Emitter from '../../libs/util/emitter.js';
	export default {
		mixins: [Emitter],
		props: {
			// v-model
			value: {
				type: Array,
				default: []
			},
			placeholder: {
				type: String,
				default: '请选择日期范围'
			},
			disabled: {
				type: Boolean,
				default: false
			},
			// 最小可选日期(不在范围内日期禁用不可选)
			minDate: {
				type: [Number, String],
				default: '1950-01-01'
			},
			/**
			 * 最大可选日期
			 * 默认最大值为今天，之后的日期不可选
			 * 2030-12-31
			 * */
			maxDate: {
				type: [Number, String],
				default: ''
			},
		},
		data() {
			return {
				show: false
			}
		},
		computed: {
			activeBgColor() {
				return this.$theme.primary
			},
			rangeColor() {
				return this.$theme.primary
			},
			rangeBgColor() {
				return this.$theme.primaryLight
			},
			defaultData() {
				return this.value.map(item => {
					return item.replace(/-0/g, '-');
				})
			}
		},
		methods: {
			// 开启日历
			handleOpen() {
				if (this.disabled) return;
				this.show = true;
			},
			change(e) {
				this.$emit('input', [e.startDate, e.endDate]);
				this.$emit('change', [e.startDate, e.endDate]);
				this.$nextTick(() => {
					this.dispatch('w-form-item', 'on-form-change', [e.startDate, e.endDate]);
				});
			}
		}
	}
</script>

<style lang="scss">
	.cc-date-range-picker {
		width: 100%;
		.mm-picker__content {
			display: flex;
			text-align: right;
			.mm-picker__placeholder {
				color: var(--light-color);
				flex: 1;
			}
			.mm-picker__text {
				flex: 1;
			}
		}
	}
</style>
